package com.zs.server;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.concurrent.Executors;

import com.zs.protocol.DownLoadProImpl;
import com.zs.protocol.DownLoadProcess;

/**
 * 提供下载服务
 * @author zhangshuqing
 *
 */
public class DownloadServer {
	
	private Selector mSelector;
	
	private DownLoadProcess process;
	

	public DownloadServer() {
		try {
			process=new DownLoadProImpl();
			mSelector=Selector.open();
			ServerSocketChannel serverChannel=ServerSocketChannel.open();
			serverChannel.bind(new InetSocketAddress( 8090));
			serverChannel.configureBlocking(false);
			serverChannel.register(mSelector, SelectionKey.OP_ACCEPT);
			Executors.newSingleThreadExecutor().execute(new ServiceThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	class ServiceThread implements Runnable{

		@Override
		public void run() {
			try {
				while(true){
					if(mSelector.select()==0){
						continue;
					}
					Iterator<SelectionKey> itor=mSelector.selectedKeys().iterator();
					while(itor.hasNext()){
						SelectionKey key=itor.next();
						itor.remove();
						process.handler(key);
						
					}
				}
			} catch (Exception e) {
				
			}
			
		}
		
	}
	
	

}
